package cn.com.fstar.core.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 获取浏览器及操作系统信息
 * @author
 *
 */
public class UserAgentUtil {
	
	
	/**
	 * 获取浏览器类型
	 * @param request
	 * @return
	 */
	public static String getBrowserType(HttpServletRequest request) {
		
		
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		Browser browser = userAgent.getBrowser();
		String browserFullName = browser.getName();
		String[] browserNames = browserFullName.split(" ");
		StringBuffer sb = new StringBuffer(); 
		if (browserNames.length > 2) {

			for (int i = 0; i < browserNames.length; i++) {
				if (i <= 1) {
					sb.append(browserNames[i]);
				}
			}
		} else {

			for (int i = 0; i < browserNames.length; i++) {
				if (i < 1) {
					sb.append(browserNames[i]);
				}
			}
		}
		return sb.toString();
		
	}
	
	/**
	 * 获取浏览器版本
	 * @param request
	 * @return
	 */
	public static String getBrowserVersion(HttpServletRequest request) {
		String browserVersion = "";
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		browserVersion = userAgent.getBrowserVersion().getVersion();
		return browserVersion;
		
	}
	
	/**
	 * 获取操作系统类型
	 * @param request
	 * @return
	 */
	public static String getOSType(HttpServletRequest request) {
		String osType = "";
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		OperatingSystem os = userAgent.getOperatingSystem();
		String osFullName = os.getName();
		if (StringUtils.isNotEmpty(osFullName)) {
			
			if (osFullName.contains(" ")) {
				osType = osFullName.substring(0, osFullName.indexOf(" "));
				return osType;
			} else {
				return osFullName;
			}
		} 
		return osType;
		
	}
	
	/**
	 * 获取操作系统版本
	 * @param request
	 * @return
	 */
	public static String getOSVersion(HttpServletRequest request) {
		String osVersion = "";
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		OperatingSystem os = userAgent.getOperatingSystem();
		String osFullName = os.getName();
		if (StringUtils.isNotEmpty(osFullName)) {
			
			if (osFullName.contains(" ")) {
				osVersion = osFullName.substring(osFullName.indexOf(" ")+1, osFullName.length());
				return osVersion;
			} else {
				return "";
			}
		}
		return osVersion;
		
	}

}
